package com.js.rtu.fragment.second;

import android.os.Bundle;
import android.widget.EditText;

import com.js.rtu.R;
import com.js.rtu.base.BaseFragment;
import com.js.rtu.config.CmdConfig;
import com.js.rtu.util.BluetoothUtils;
import com.js.rtu.util.CmdUtils;
import com.js.rtu.util.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 22_09设置终端工作参数
 * 模拟量表计供电时间(单位为毫秒)
 * 2 byte
 * Created by zwz on 2020/6/22.
 */
public class Cmd_22_09Fragment extends BaseFragment {



    @BindView(R.id.edt_input)
    EditText edtInput;



    public static Cmd_22_09Fragment newInstance() {
        Cmd_22_09Fragment fragment = new Cmd_22_09Fragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_second_cmd_22_09;
    }

    @Override
    protected void initView() {

    }






    private void set() {
        String data = edtInput.getText().toString();
        if (data.isEmpty()) {
            toastShow("请填写参数，0-65535");
            return;
        }
        int interval = Integer.parseInt(data);
        if (interval > 0 && interval <= 65535) {
            data = String.format("%04x", interval);
            String msg = CmdConfig.CMD_22_09 + " " + data.substring(2, 4) + " " + data.substring(0, 2);
            sendData(msg);
        } else {
            toastShow("0-65535,大于0");
        }

    }

    private void sendData(String data) {
        String cmd = CmdUtils.getCmd(CmdConfig.CMD_22, data);

        BluetoothUtils.send(cmd, new BluetoothUtils.onCallback() {
            @Override
            public void onReceive(String msg) {
                dismissLoadingDialog();

                String[] data = msg.split(" ");
                if (data.length < 18) {
                    ToastUtil.info(msg);
                    return;
                }
                if (data[12].equals(CmdConfig.CMD_22)
                        && data[13].equals(CmdConfig.CMD_22_09)) {
                    if (data[14].equals(CmdConfig.SUCCECC)) {
                        ToastUtil.success("设置成功");
                    } else {
                        ToastUtil.error("设置失败");
                    }

                }


            }

            @Override
            public void onFail(String err) {
                toastShow(err);
                dismissLoadingDialog();
            }
        });
    }

    @OnClick(R.id.btn_set)
    public void onViewClicked() {
        set();
    }

}
